package com.mishow.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.adapter.LabelVOTypeAdapter;
import com.mishow.inteface.LabelSelectRefreshInteface;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.core.Response;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.LabelVOResponse;
import com.mishow.request.result.LabelVO;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.ToastUtil;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.EmptyDataLayout;

/**
 * 
 * 作者：wei.miao <br/>
 * 描述：丽质资料标签选择器
 */
public class LabelVOTypeActivity extends BaseActivity implements LabelSelectRefreshInteface{

	private Button btn_back;
	private TextView title_right;
	
	private ListView lv_labeltypes;
	
	private EmptyDataLayout empty_labeltypes;

	private LabelVOTypeAdapter mLabelVOTypeAdapter;
	
	/** 用户上次已选择的丽质标签 **/
	private ArrayList<String> mStrings;

	private String mTagType;

	/** 默认多选 **/
	boolean mIsRadio;

	/** 丽质类型显示标签 **/
	private ArrayList<String> mProfessionTypeTags = new ArrayList<String>();
	
	private ArrayList<LabelVO> mLabelVo = new ArrayList<>();
	
	private SharedPreferencesUtil mShPreferencesUtil;

	/**
	 * @param type
	 *            tag类型，可以类型为profession_type(职业类型)
	 * @param tags
	 *            已选择的标签列表
	 * @param title
	 *            页面标题
	 * @param requestCode
	 *            区分同一个页面请求不同的标签
	 * @param isRadio
	 *            单选传true
	 */
	public static void intoActivityForResult(Context ctx, String type,
			ArrayList<String> tags, String title, int requestCode,
			boolean isRadio) {
		Intent intent = new Intent(ctx, LabelVOTypeActivity.class);
		intent.putExtra(Constants.TAG_TYPE, type);
		intent.putExtra(Constants.TAG_TITLE, title);
		intent.putExtra(Constants.TAG_IS_RADIO, isRadio);
		if (tags != null && tags.size() > 0) {
			intent.putExtra(Constants.SELECTED_TAGS, tags);
		}
		((BaseActivity) ctx).startActivityForResult(intent, requestCode);
	}

	/**
	 * @param type
	 *            tag类型，可选类型为(丽质资料,才艺类型)
	 * @param tags
	 *            已选择的标签列表
	 * @param title
	 *            页面标题
	 * @param requestCode
	 *            区分同一个页面请求不同的标签
	 */
	public static void intoActivityForResult(Context ctx, String type,
			ArrayList<String> tags, String title, int requestCode) {
		intoActivityForResult(ctx, type, tags, title, requestCode, false);
	}

	@Override
	protected void initData() {

		if (getIntent().getStringExtra(Constants.TAG_TYPE) != null) {
			
			mTagType = getIntent().getStringExtra(Constants.TAG_TYPE);
			
		} else {
			ToastUtil.show(mContext, "数据错误");
			finish();
		}
		
		mIsRadio = getIntent().getBooleanExtra(Constants.TAG_IS_RADIO, false);

		if (getIntent().getParcelableArrayListExtra(Constants.SELECTED_TAGS) != null) {
			mStrings = getIntent().getStringArrayListExtra(Constants.SELECTED_TAGS);
		} else {
			mStrings = new ArrayList<>();
		}
		
		mShPreferencesUtil = new SharedPreferencesUtil(mContext);
	}

	@Override
	protected void initView(Bundle savedInstanceState) {

		setContentView(R.layout.activity_label_type);

		btn_back = (Button) findViewById(R.id.btn_back);
		title_right = (TextView) findViewById(R.id.title_right);
		
		lv_labeltypes = (ListView) findViewById(R.id.lv_labeltypes);
		empty_labeltypes = (EmptyDataLayout) findViewById(R.id.empty_labeltypes);

	}

	@Override
	protected void setAttribute() {

		if (getIntent().getStringExtra(Constants.TAG_TITLE) != null) {
			setTitle(getIntent().getStringExtra(Constants.TAG_TITLE));
		}
		
		mLabelVOTypeAdapter = new LabelVOTypeAdapter(mContext,mStrings,mLabelVo,mIsRadio,this);
		lv_labeltypes.setAdapter(mLabelVOTypeAdapter);
		
		btn_back.setOnClickListener(onClickListener);
		title_right.setOnClickListener(onClickListener);
		title_right.setVisibility(View.VISIBLE);
		title_right.setText("确定");
		title_right.setTextColor(mContext.getResources().getColor(
				R.color.search_pop_color));

		if (mTagType.equals("skill_type")) {
			
			getSkillTypeTagsFromApi();
		}else{
			// 服务端获取标签
			getTagsFromApi();
		}
		// 选择标签的数量
		refreshSelectedCount();
		
	}
	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.title_right:// 保存
				if (mTagType.equals("skill_type")) {
					Intent intent = new Intent();
					intent.putExtra(Constants.SELECTED_TAGS, mStrings);
					setResult(RESULT_OK, intent);
					finish();
				}else{
					doUpdageTagsFromApi();
				}
				break;
			default:
				break;
			}
		}
	};
	
	/**
	 * 服务端获取所有丽质标签
	 */
	private void getTagsFromApi() {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		
		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,HttpUrlConstant.GET_VERY_LABEL);
		OnResponseListener<LabelVOResponse> listener = new OnResponseListener<LabelVOResponse>(this) {

			@Override
			public void onSuccess(LabelVOResponse response) {

				ArrayList<LabelVO> labelVo = response.getBody().getResult();
				mLabelVo.addAll(labelVo);
				mLabelVOTypeAdapter.notifyDataSetChanged();
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<LabelVOResponse>(
				Request.Method.POST, postUrl, LabelVOResponse.class,
				listener, listener).setParams(lastParams));
	}

	/**
	 * 才艺类型标签
	 */
	private void getSkillTypeTagsFromApi() {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		
		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,HttpUrlConstant.GET_QUERY_VOCATIONAL);
		OnResponseListener<LabelVOResponse> listener = new OnResponseListener<LabelVOResponse>(this) {

			@Override
			public void onSuccess(LabelVOResponse response) {

				ArrayList<LabelVO> labelVo = response.getBody().getResult();
				mLabelVo.addAll(labelVo);
				mLabelVOTypeAdapter.notifyDataSetChanged();
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<LabelVOResponse>(
				Request.Method.POST, postUrl, LabelVOResponse.class,
				listener, listener).setParams(lastParams));
	}

	/**
	 * 服务端更新丽质标签
	 */
	private void doUpdageTagsFromApi() {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", mShPreferencesUtil.getUserId());
		
		params.put("statureHeight", "");//身高(单位：cm)
		params.put("statureWeight", "");//体重(单位：kg)
		params.put("statureBust", ""); //胸围
		params.put("statureWaist", "");//腰围
		params.put("statureHips", "");//臀围
		params.put("statureFeet", ""); //鞋码
		params.put("statureMeasurements", "");//三围(40—40—40)
		params.put("statureCup", "");//罩杯(A、B、C、D、E、F)
		params.put("statureLeg", "");//腿长(单位：cm)
		params.put("statureExcelled", "");//擅长(多个标签，使用“，”隔开)
		if (mProfessionTypeTags != null && mProfessionTypeTags.size() > 0) {
			StringBuilder sBuilderTreatment = new StringBuilder();
			for (String tag : mProfessionTypeTags) {
				sBuilderTreatment.append(tag + ",");
			}
			String treatment = sBuilderTreatment.substring(0,
					sBuilderTreatment.length() - 1);
			params.put("statureLabel", treatment);//标签(多个标签，使用“，”隔开)
		} else {
			params.put("statureLabel", "");//标签(多个标签，使用“，”隔开)
		}
		
		params.put("statureSchool", "");//学校

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,HttpUrlConstant.UPDATE_USER_STATURE);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(this) {

			@Override
			public void onSuccess(Response response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				finish();
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(
				Request.Method.POST, postUrl, Response.class,
				listener, listener).setParams(lastParams));

	}

	/**
	 * refresh标题栏显示的选择数
	 */
	private void refreshSelectedCount() {
		int total = mStrings.size();
		title_right.setText("已选 (" + total + ")");
	}

	
	@Override
	public void refreshSelectedCount(ArrayList<String> selectTags) {
		if (!mTagType.equals("skill_type")){
			mProfessionTypeTags = selectTags;
		}
		refreshSelectedCount();
		
	}



}
